package com.lecture.java8.graph.demo01;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class VillageGraphGUI extends JFrame {
    private GraphManager graphManager = new GraphManager();

    public VillageGraphGUI() {
        setTitle("村村通管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("文件");
        JMenuItem loadItem = new JMenuItem("加载数据");
        JMenuItem saveItem = new JMenuItem("保存数据");

        loadItem.addActionListener(e -> loadData());
        saveItem.addActionListener(e -> saveData());

        fileMenu.add(loadItem);
        fileMenu.add(saveItem);
        menuBar.add(fileMenu);

        setJMenuBar(menuBar);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        panel.add(scrollPane, BorderLayout.CENTER);

        JButton addButton = new JButton("添加村庄");
        JButton addRoadButton = new JButton("添加道路");
        JButton isConnectedButton = new JButton("判断连通性");
        JButton tspButton = new JButton("村村通方案");

        addButton.addActionListener(e -> addVillageDialog());
        addRoadButton.addActionListener(e -> addRoadDialog());
        isConnectedButton.addActionListener(e -> checkConnectivity(textArea));
        tspButton.addActionListener(e -> findTsp(textArea));

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(addButton);
        buttonPanel.add(addRoadButton);
        buttonPanel.add(isConnectedButton);
        buttonPanel.add(tspButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        add(panel);
    }

    private void loadData() {
        List<Village> villages = FileManager.loadVillages();
        List<Road> roads = FileManager.loadRoads();
        villages.forEach(graphManager::addVillage);
        roads.forEach(graphManager::addRoad);
    }

    private void saveData() {
        List<Village> villages = new ArrayList<>(graphManager.getVillages().values());
        FileManager.saveVillages(villages);
        FileManager.saveRoads(new ArrayList<>()); // TODO: Save roads
    }

    private void addVillageDialog() {
        // Add village dialog implementation
    }

    private void addRoadDialog() {
        // Add road dialog implementation
    }

    private void checkConnectivity(JTextArea textArea) {
        boolean connected = graphManager.isConnected();
        textArea.setText("是否连通: " + connected);
    }

    private void findTsp(JTextArea textArea) {
        // Find TSP solution and display it
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            VillageGraphGUI ui = new VillageGraphGUI();
            ui.setVisible(true);
        });
    }
}
